package cn.mrlong.base.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities

/**
 * 作者：BINGO
 * 时间：2021/03/31 13:44
 */
class NetWorkUtils {
    /**
     * 判断是否有网络连接
     * @param context Context
     * @return Boolean
     */
    fun isConnected(context: Context): Boolean {
        val cn: ConnectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            val activeNetwork = cn.activeNetwork ?: return false
            val networkCapabilities = cn.getNetworkCapabilities(activeNetwork) ?: return false
            return networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
        } else {
            val mNetworkInfo = cn.activeNetworkInfo ?: return false
            return mNetworkInfo.isConnected
        }
    }

    /**
     * 判断是不是wifi
     * @param context Context
     * @return Boolean
     */
    fun isWifi(context: Context): Boolean {
        val cn: ConnectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            val network = cn.activeNetwork ?: return false
            val capabilities = cn.getNetworkCapabilities(network) ?: return false
            return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
        } else {
            val networkInfo = cn.activeNetworkInfo ?: return false
            return networkInfo.type == ConnectivityManager.TYPE_WIFI
        }
    }

    /**
     * 判断是不是移动蜂窝数据
     * @param context Context
     * @return Boolean
     */
    fun isMobile(context: Context): Boolean {
        val cn: ConnectivityManager =
            context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            val network = cn.activeNetwork ?: return false
            val capabilities = cn.getNetworkCapabilities(network) ?: return false
            return capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)
        } else {
            val networkInfo = cn.activeNetworkInfo ?: return false
            return networkInfo.type == ConnectivityManager.TYPE_MOBILE
        }
    }
}